package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dto.EmpDto;
import com.itheima.dto.EmpLoginDto;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import com.itheima.utils.MyJwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private MyJwtUtils myJwtUtils;
    /*@Override
    public PageBean<Emp> getByPage(Integer pageNum, Integer pageSize) {
        //计算出省略的页数，pageNum是前端给的查询的第几页
        Integer start=(pageNum-1)*pageSize;
        //通过mapper接口中的方法算出总页数
        Long total = empMapper.getTotal();
        //通过mapper接口中的方法算出当前页数据
        List<Emp> emps = empMapper.getByPage(start, pageSize);
        return new PageBean<>(total,emps);
    }*/

    @Override
    public PageBean<Emp> getByPage(Integer pageNum, Integer pageSize, EmpDto dto) {
        PageHelper.startPage(pageNum, pageSize);
         Page<Emp> emps=(Page<Emp>) empMapper.getByPage(dto);

        return new PageBean<>(emps.getTotal(),emps.getResult());
    }

    @Override
    public int deleteEmp(Integer[] ids) {
        return empMapper.deleteEmp(ids);
    }

    @Override
    public int insertEmp(Emp emp) {
        emp.setPassword("123456");
        emp.setEntrydate(LocalDate.now());
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        return empMapper.insertEmp(emp);
    }

    @Override
    public Result login(EmpLoginDto dto) {
        Emp emp=empMapper.findByUsernameAndPassword(dto);
        if (emp==null){
            return Result.error("NOT_LOGIN");
        }
        Map<String,Object> map=new HashMap<>();
        map.put("id" ,emp.getId());
        map.put("name",emp.getName());
        String jwt = myJwtUtils.createJwt(map);
        return Result.success(jwt);
    }
}
